package com.example.pluginlib

import com.android.build.api.transform.*
import com.android.build.gradle.AppExtension
import com.android.build.gradle.internal.pipeline.TransformManager
import com.android.ide.common.internal.WaitableExecutor
import org.gradle.api.Plugin
import org.gradle.api.Project

import java.util.concurrent.Callable


//需要注意导包的问题
class MyPlugin extends Transform implements Plugin<Project> {

    private WaitableExecutor waitableExecutor = WaitableExecutor.useGlobalSharedThreadPool()



    @Override
    void apply(Project project) {
        System.out.println("========================")
        System.out.println("hello gradle plugin!")
        System.out.println("========================")

        //registerTransform
        def android = project.extensions.getByType(AppExtension)
        android.registerTransform(this)
    }


    @Override
    String getName() {
        return "com.plugin.gradle"
    }

    @Override
    void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
        System.out.println("========================")
        System.out.println("hello transform plugin!")
        System.out.println("========================")

        println '--------------- LifecyclePlugin visit start --------------- '

        def startTime = System.currentTimeMillis()
        Collection<TransformInput> inputs = transformInvocation.inputs
        TransformOutputProvider outputProvider = transformInvocation.outputProvider
        //删除之前的输出
        if (outputProvider != null)
            outputProvider.deleteAll()


        //遍历inputs
        inputs.each { TransformInput input ->
            //遍历directoryInputs
            input.directoryInputs.each { DirectoryInput directoryInput ->
                //异步并发处理jar/class
                waitableExecutor.execute(new Callable<Void>() {
                    @Override
                    Void call() throws Exception {
                        //处理directoryInputs
                        handleDirectoryInput(directoryInput, outputProvider)
                        return null
                    }
                })
            }

            //遍历jarInputs
            input.jarInputs.each { JarInput jarInput ->
                //异步并发处理jar/class
                waitableExecutor.execute(new Callable<Void>() {
                    @Override
                    Void call() throws Exception {
                        //处理jarInputs
                        handleJarInputs(jarInput, outputProvider)
                        return null
                    }
                })
            }
        }
        //等待所有任务结束
        waitableExecutor.waitForTasksWithQuickFail(true)


        def cost = (System.currentTimeMillis() - startTime) / 1000
        println '--------------- LifecyclePlugin visit end --------------- '
        println "LifecyclePlugin cost ： $cost s"
    }


    /**
     * 处理文件目录下的class文件
     */
    static void handleDirectoryInput(DirectoryInput directoryInput, TransformOutputProvider outputProvider) {
        //是否是目录
        if (directoryInput.file.isDirectory()) {
            //列出目录所有文件（包含子文件夹，子文件夹内文件）
            directoryInput.file.eachFileRecurse { File file ->
                def name = file.name
                println '----------- deal with "class" file <' + name + '> -----------'
            }
        }
    }

    static void handleJarInputs(JarInput jarInput, TransformOutputProvider outputProvider) {
        if (jarInput.file.getAbsolutePath().endsWith(".jar")) {
            //重名名输出文件,因为可能同名,会覆盖
            def jarName = jarInput.name
            println '----------- deal with "jarName" file <' + jarName + '> -----------'
        }
    }


    @Override
    Set<QualifiedContent.ContentType> getInputTypes() {
        return TransformManager.CONTENT_CLASS
    }

    @Override
    Set<? super QualifiedContent.Scope> getScopes() {
        return TransformManager.SCOPE_FULL_PROJECT
    }

    @Override
    boolean isIncremental() {
        return true
    }
}